package com.michael.demos.base.thread.juc.lock;

/**
 * 类功能描述:
 * <pre>
 *   不可重入锁示例
 *   不可重入锁 —— 代码编写不规范会造成死锁
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/8/14 10:34
 */
public class NonreentrantLockDemo {
	public static void main(String[] args) throws InterruptedException {
		NonreentrantLockUse use = new NonreentrantLockUse();
		// 以下代码会造成死锁
		use.willGodie();
	}
}

class NonreentrantLockUse {

	NonreentrantLock lock = new NonreentrantLock();

	public void willGodie() throws InterruptedException {
		lock.lock();
		test();
		lock.unlock();
	}

	public void test() throws InterruptedException {
		lock.lock();
		//do something
		lock.unlock();
	}
}

/** 不可重入锁 */
class NonreentrantLock {
	private boolean isLocked = false;

	public synchronized void lock() throws InterruptedException {
		while (isLocked) {
			wait();
		}
		isLocked = true;
	}

	public synchronized void unlock() {
		isLocked = false;
		notify();
	}
}
